package com.whity.towerdefense.model;

import java.io.IOException;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.whity.towerdefense.Utils;

import android.util.Log;

public class UnitFactory
{
	// =============================================================
	// Private attributs
	
	private static final String					TAG = "com.djm.test03.model";
	
	private static HashMap<String, UnitType> 	m_UnitTypes = new HashMap<String, UnitType>();
	private static int							m_CountCreatedType = 0;
	
	// =============================================================
	// Public functions :
	
	/*
	public UnitFactory()
	{
		
	}*/
	
	public static Unit CreateUnit(String p_ID, float p_X, float p_Y)
	{
		UnitType unitType = null;
		if((unitType = m_UnitTypes.get(p_ID)) != null)
		{
			Unit res = unitType.CreateUnit(p_X, p_Y);
			return res;
		}
		return null;
	}
	
	public static UnitType GetUnitType(String p_ID)
	{
		return m_UnitTypes.get(p_ID);
	}
	
	public static void SetUnitType(String p_ID, UnitType p_Type)
	{
		m_UnitTypes.put(p_ID, p_Type);
	}
	
	public static String CreateNewType(XmlPullParser p_XmlParser) throws ParsingException
	{
		if(!p_XmlParser.getName().equals("Unit"))
    	{
			Log.w(TAG, "Can't create a Unit type with an Xml item : " + p_XmlParser.getName());
			throw(new ParsingException("Can't create a Unit type with an Xml item : " + p_XmlParser.getName()));
		}
		
		// We get the new Id of this new type
		String NewTypeId = "AutomaticType" + m_CountCreatedType;
		m_CountCreatedType++;
		
		// Create the new Type
		UnitType newType;
		try
		{
			newType = new UnitType(p_XmlParser);
			m_UnitTypes.put(NewTypeId, newType);
		}
		catch (XmlPullParserException e)
		{
			Log.w(TAG, "Can't create a Unit type with an Xml item : " + p_XmlParser.getName());
			System.exit(Utils.UNIT_TYPE_PARSING_FATAL_ERROR);
		} catch (IOException e)
		{
			Log.w(TAG, "Can't create a Unit type with an Xml item : " + p_XmlParser.getName());
			System.exit(Utils.UNIT_TYPE_PARSING_FATAL_ERROR);
		}
		
		return NewTypeId;
	}
	
	// =============================================================
}
